package com.matriq.cloudmanager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.entity.Timtable;
import com.matriq.cloudmanager.service.AccountService;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.lgpage.activity.BaseActivity;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Checker.StringUtils;
import net.lgpage.util.Cleaner;
import net.lgpage.util.CompareUtil.DateCompareUtil;
import net.lgpage.util.FormatUtil.DateFormatUtil;

public class ClassScheduleActivity extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_class_schedule);
		setViews();
		setEvents();
		loadData();
	}

	TextView tv_during;
	android.support.v4.widget.SwipeRefreshLayout srl;
	android.support.v7.widget.RecyclerView rcy_class_schedule;
	Button bt_next;
	TextView tv_title;
	ImageButton ll_back;
	Button bt_pre;

	private void setViews() {
		tv_during = (TextView) this.findViewById(R.id.tv_during);
		srl = (android.support.v4.widget.SwipeRefreshLayout) this.findViewById(R.id.srl);
		rcy_class_schedule = (android.support.v7.widget.RecyclerView) this.findViewById(R.id.rcy_class_schedule);
		rcy_adp = new RcyAdp();
		rcy_class_schedule.setLayoutManager(new LinearLayoutManager(this));
		rcy_class_schedule.setAdapter(rcy_adp);
		bt_next = (Button) this.findViewById(R.id.bt_next);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		ll_back = (ImageButton) this.findViewById(R.id.ll_back);
		bt_pre = (Button) this.findViewById(R.id.bt_pre);
	}

	private void setEvents() {
		bt_next.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int next = hasNextWeek();
				showWeek(next);
			}
		});
		bt_pre.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int pre = hasPreWeek();
				showWeek(pre);
			}
		});
		srl.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
	}

	private void ctrlPreOrNextBt() {
		if (hasNextWeek() != weekNo) {
			bt_next.setVisibility(View.VISIBLE);
		} else {
			bt_next.setVisibility(View.INVISIBLE);
		}
		if (hasPreWeek() != weekNo) {
			bt_pre.setVisibility(View.VISIBLE);
		} else {
			bt_pre.setVisibility(View.INVISIBLE);
		}
	}

	Object obj;

	public void setData(Object obj) {
		this.obj = obj;
		tv_during.setText(null);
		tv_title.setText(null);
	}

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		LinearLayout ll[] = new LinearLayout[2];
		TextView tv_day;
		TextView tv_month;
		View v_line;
		//View v_line2;
		View blank;
		TextView tv[] = new TextView[8];

		public RcyViewHolder(View view) {
			super(view);
		}
	}

	RcyAdp rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}

		@Override
		public void onBindViewHolder(RcyViewHolder h, final int position) {
			final Timtable obj = rcylist.get(position);
			try {
				Date d = f.parse(obj.getDate());
				Calendar cal = Calendar.getInstance();
				cal.setTime(d);
				h.tv_month.setText((cal.get(Calendar.MONTH) + 1) + "");
				String week = "星期" + DateFormatUtil.getWeekNameFromCalendar(cal);
				h.tv_day.setText(obj.getDate() + " " + week);
			} catch (ParseException e) {

			}
			if (StringUtils.isEmpty(obj.getAM())) {
				h.ll[0].setVisibility(View.GONE);
			} else {
				h.ll[0].setVisibility(View.VISIBLE);
			}
			if (StringUtils.isEmpty(obj.getPM())) {
				h.ll[1].setVisibility(View.GONE);
			} else {
				h.ll[1].setVisibility(View.VISIBLE);
			}
			if (!StringUtils.isEmpty(obj.getPM())&&!StringUtils.isEmpty(obj.getAM())){
				h.v_line.setVisibility(View.VISIBLE);
			}else{
				h.v_line.setVisibility(View.GONE);
			}
			String str = obj.getAM();
			String str1;
			try {
				str1 = str.substring(0, str.indexOf("[授课教师"));
			} catch (Exception e) {
				str1 = str;
			}
			h.tv[0].setText(str1);
			String str2;
			try {
				str2 = str.substring(str.indexOf("授课教师"), str.indexOf("上课地点"));
			} catch (Exception e) {
				str2 = "授课教师:";
			}
			h.tv[1].setText(str2);
			String str3;
			try {
				str3 = str.substring(str.indexOf("上课地点"), str.lastIndexOf("]"));
			} catch (Exception e) {
				str3 = "上课地点:";
			}
			h.tv[2].setText(str3);
			
			 str = obj.getPM();
				try {
					str1 = str.substring(0, str.indexOf("[授课教师"));
				} catch (Exception e) {
					str1 = str;
				}
			h.tv[4].setText(str1);
			try {
				str2 = str.substring(str.indexOf("授课教师"), str.indexOf("上课地点"));
			} catch (Exception e) {
				str2 = "授课教师:";
			}
			h.tv[5].setText(str2);
			try {
				str3 = str.substring(str.indexOf("上课地点"), str.lastIndexOf("]"));
			} catch (Exception e) {
				str3 = "上课地点:";
			}
			h.tv[6].setText(str3);
			if(position == getItemCount()-1){
				h.blank.setVisibility(View.VISIBLE);
			}else{
				h.blank.setVisibility(View.GONE);
			}
			h.itemView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					
				}
			});
		}

		@SuppressLint("InflateParams")
		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getLayoutInflater().inflate(R.layout.rcy_class_schedule2, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.ll[0] = (LinearLayout) cv.findViewById(R.id.ll0);
			h.ll[1] = (LinearLayout) cv.findViewById(R.id.ll1);
			//h.ll[2] = (LinearLayout) cv.findViewById(R.id.ll2);
			h.tv_day = (TextView) cv.findViewById(R.id.tv_day);
			h.tv_month = (TextView) cv.findViewById(R.id.tv_month);
			h.v_line = (View) cv.findViewById(R.id.v_line);
			//h.v_line2 = (View) cv.findViewById(R.id.v_line2);
			h.tv[0] = (TextView) cv.findViewById(R.id.tv0);
			h.tv[1] = (TextView) cv.findViewById(R.id.tv1);
			h.tv[2] = (TextView) cv.findViewById(R.id.tv2);
			
			h.tv[3] = (TextView) cv.findViewById(R.id.tv3);
			h.tv[4] = (TextView) cv.findViewById(R.id.tv4);
			h.tv[5] = (TextView) cv.findViewById(R.id.tv5);
			
			h.tv[6] = (TextView) cv.findViewById(R.id.tv6);
			h.tv[7] = (TextView) cv.findViewById(R.id.tv7);
			h.blank = cv.findViewById(R.id.v_blank);
			return h;
		}
	}

	List<Timtable> rcylist;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(this);
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<List<Timtable>> {

		public RcyListTask(Context context) {
			super(context);
		}

		@Override
		public List<Timtable> doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().timtable();
		}

		@Override
		public void onPostExecuteX(List<Timtable> result) {
			if (result == null) {
				return;
			} else {
				baselist = result;
				Collections.sort(baselist, comparator);
				doFilter();
				showWeek(weekNo);
			}
		}
	}
	Comparator<Timtable> comparator = new Comparator<Timtable>() {

		@Override
		public int compare(Timtable lhs, Timtable rhs) {
			Date ld = null;
			Date rd = null;
			try {
				ld = f.parse(lhs.getDate());
			} catch (ParseException e) {
				ld = null;
			}
			try {
				rd = f.parse(rhs.getDate());
			} catch (ParseException e) {
				rd = null;
			}
			if (ld == null && rd == null)
				return 0;
			if (ld == null)
				return -1;
			if (rd == null)
				return 0;
			return ld.compareTo(rd);
		}
	};
	private void showWeek(int index) {
		rcylist = map.get(index);
		if(rcylist == null||rcylist.size() == 0){
			int redrict = hasNextWeek();
			if(redrict !=index){
				showWeek(index);
			}else{
				redrict = hasPreWeek();
				if(redrict !=index){
					showWeek(redrict);
				}else{
					rcy_adp.notifyDataSetChanged();
					String text = buildBetweenString(index);
					tv_during.setText(text);
					weekNo = index;
					ctrlPreOrNextBt();
				}
			}
		}else{
			rcy_adp.notifyDataSetChanged();
			String text = buildBetweenString(index);
			tv_during.setText(text);
			weekNo = index;
			ctrlPreOrNextBt();
		}
		
	}

	private String buildBetweenString(int weekno) {
		Calendar weekstart = Calendar.getInstance();
		int dayofweek = weekstart.get(Calendar.DAY_OF_WEEK);
		System.out.println(dayofweek);
		weekstart.add(Calendar.DAY_OF_MONTH, -dayofweek + 2 + 7 * weekno);
		StringBuffer sb = new StringBuffer();
		sb.append(f.format(weekstart.getTime()));
		sb.append("\n");
		weekstart.add(Calendar.DAY_OF_MONTH, 6);
		sb.append(f.format(weekstart.getTime()));
		return sb.toString();
	}

	private int hasPreWeek() {
		int pre = weekNo;
		for (int i = 0; i < map.size(); i++) {
			int no = map.keyAt(i);
			if (no < weekNo) {
				if (pre == weekNo)
					pre = no;
				else if (no > pre)
					pre = no;
			}
		}
		return pre;
	}

	private int hasNextWeek() {
		int next = weekNo;
		for (int i = 0; i < map.size(); i++) {
			int no = map.keyAt(i);
			if (no > weekNo) {
				if (next == weekNo)
					next = no;
				else if (no < next)
					next = no;
			}
		}
		return next;
	}

	int weekNo = 0;
	SparseArray<List<Timtable>> map;
	List<Timtable> baselist;

	private void doFilter() {
		initNowMonday();
		map = new SparseArray<>();
		for (int i = 0; i < baselist.size(); i++) {
			Timtable t = baselist.get(i);
			int bet = (int) weekBetween(t.getDate());
			List<Timtable> list = map.get(bet);
			if (list == null) {
				list = new ArrayList<>();
				map.put(bet, list);
			}
			list.add(t);
		}
	}

	Date nowMonday;
	SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");

	private void initNowMonday() {
		Date d = null;
		try {
			d = f.parse(f.format(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar weekstart = Calendar.getInstance();
		weekstart.setTime(d);
		int dayofweek = weekstart.get(Calendar.DAY_OF_WEEK);
		weekstart.add(Calendar.DAY_OF_MONTH, -dayofweek + 2);
		nowMonday = weekstart.getTime();
	}

	private long weekBetween(String yyyyMMdd) {
		Calendar now = Calendar.getInstance();
		now.add(Calendar.DAY_OF_MONTH, -3);
		Date d = null;
		try {
			d = f.parse(yyyyMMdd);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int bt = (int) (DateCompareUtil.dayCompare(nowMonday, d));
		if (bt < 0)
			return (bt +1)/  7 - 1;
		return bt / 7;
	}


	private void loadData() {

		refeshRcyList();
	}
	@Override
	public void onDestroy() {
		Cleaner.cleanTask(rcylistTask);

		super.onDestroy();
	}

}